//
//  CalendarPreviewView.swift
//  YLH
//
//  Created by qinjiangtao on 2024/1/15.
//

import UIKit
import YYText
import DZNEmptyDataSet

class CalendarPreviewView: UIView {
    
//    var addMatterBlock: voidBlock?
    
    private var bgView = UIView()
    private var dateL = UILabel()
    private var addBtn = UIButton()
    private var dataArr = [ScheduleListModel]()

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addUI()
    }
    
    var model = CalendarModelListModel() {
        didSet {
            dateL.text = model.allDate
            getData()
        }
    }
    
    private func getData() {
        QINetworkManager.requestJson(urlStr: "/Calendar/detail", method: .get, parameters: ["date": model.allDate]) { json in
            self.dataArr = json.arrayObject?.kj.modelArray(ScheduleListModel.self) ?? [ScheduleListModel]()
            self.tableView.reloadData()
        }
    }
    
    private func addUI() {
        
        bgView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT)
        bgView.backgroundColor = UIColor(white: 0, alpha: 0.5)
        self.addSubview(bgView)
        
        dateL = UILabel().then({
            $0.frame = CGRect(x: 20, y: SCREEN_HEIGHT / 2 - 250, width: 300, height: 28)
            $0.text = ""
            $0.textColor = .white
            $0.font = SYSFONTBOLD(ofSize: 20)
        })
        bgView.addSubview(dateL)
        
        bgView.addSubview(tableView)
        
        addBtn = UIButton().then {
            $0.frame = CGRect(x: 40, y: SCREEN_HEIGHT / 2 + 200, width: tableView.width - 40, height: 40)
            $0.backgroundColor = MainColor
            $0.titleLabel?.font = SYSFONT(ofSize: 15)
            $0.setTitle("添加事项", for: .normal)
            $0.setTitleColor(.white, for: .normal)
            $0.addRoundedCorners(withRadius: 8)
            $0.addTarget(self, action: #selector(addBtnClick), for: .touchUpInside)
        }
        bgView.addSubview(addBtn)
        
        let closeBtn = UIButton().then {
            $0.frame = CGRect(x: SCREEN_WIDTH / 2 - 20, y: tableView.bottom + 10, width: 40, height: 40)
            $0.setImage(UIImage(named: "日历关闭"), for: .normal)
            $0.addTarget(self, action: #selector(closeBtnClick), for: .touchUpInside)
        }
        self.addSubview(closeBtn)
    }
    
    @objc private func bgViewClick() {
        bgView.removeFromSuperview()
        self.removeAllSubviews()
        self.removeFromSuperview()
    }
    
    @objc private func addBtnClick() {
//        if addMatterBlock != nil {
//            addMatterBlock!()
//        }
        
//        let dateFormatter = DateFormatter()
//        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // 设置日期格式
//        var currentDate = dateFormatter.string(from: Date())
//        let rang = currentDate.index(currentDate.startIndex, offsetBy: 0)..<currentDate.index(currentDate.startIndex, offsetBy: 10)
//        currentDate.replaceSubrange(rang, with: model.allDate)
        
//        var dataModel = ScheduleListModel()
//        dataModel.starttime = "\(model.allDate) 00:00:00"
        let ctl = NewSchedulerViewController()
        ctl.startDate = "\(model.allDate) 00:00:00"
        self.viewController().navigationController?.pushViewController(ctl, animated: true)
        bgViewClick()
        QINPopUpTool.sharedInstance().clear()
    }
    
    @objc private func closeBtnClick() {
        QINPopUpTool.sharedInstance().clear()
    }
    
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.frame = CGRect(x: 20, y: SCREEN_HEIGHT / 2 - 200, width: SCREEN_WIDTH - 40, height: 450)
        tableView.backgroundColor = .white
        tableView.separatorStyle = .none
        tableView.emptyDataSetSource = self
        tableView.emptyDataSetDelegate = self
        tableView.delegate = self
        tableView.dataSource = self
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        } else {}
        return tableView
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

extension CalendarPreviewView: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        10
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        10
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        UIView()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        dataArr.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        100
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = CalendarPreviewCell()
        cell.selectionStyle = .none
        cell.model = dataArr[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let ctl = NewSchedulerViewController()
        ctl.model = dataArr[indexPath.row]
        self.viewController().navigationController?.pushViewController(ctl, animated: true)
        QINPopUpTool.sharedInstance().clear()
    }
    
    // 删除
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        .delete
    }
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        let model = dataArr[indexPath.row]
        QINetworkManager.requestJson(urlStr: "/Calendar/delete", parameters: ["id": model.id]) { json in
            print(json)
            self.dataArr.removeAll()
            self.getData()
        }
    }
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        true
    }
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        "删除"
    }
    func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
        false
    }
}


extension CalendarPreviewView: DZNEmptyDataSetSource, DZNEmptyDataSetDelegate{
    
    // 是否显示DZNEmptyDataSet这个控件
    func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool {
        return dataArr.count > 0 ? false : true
    }
    
    func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool {
        true
    }
    
    func buttonTitle(forEmptyDataSet scrollView: UIScrollView!, for state: UIControl.State) -> NSAttributedString! {
        let attStr = NSMutableAttributedString(string: "当天暂无事项")
        let rang: NSRange = NSRange(location: 0, length: attStr.length)
        attStr.addAttribute(NSAttributedString.Key.font, value: SYSFONTBOLD(ofSize: 18), range: rang)
        attStr.addAttribute(NSAttributedString.Key.foregroundColor, value: Color666666, range: rang)
        return attStr
    }
    
    
}


class CalendarPreviewCell: UITableViewCell {
    
    private let bgView = UIView()
    private var titileL = UILabel()
    private var dateL = UILabel()
    private var detailL = YYLabel()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        addUI()
    }
    func addUI() {
        
        bgView.frame = CGRect(x: 10, y: 5, width: SCREEN_WIDTH - 60, height: 90)
        bgView.addRoundedCorners(withRadius: 10)
        self.addSubview(bgView)
        
        titileL = UILabel().then({
            $0.frame = CGRect(x: 10, y: 10, width: 100, height: 20)
            $0.text = "饮食计划"
            $0.textColor = Color666666
            $0.font = SYSFONT(ofSize: 14)
        })
        bgView.addSubview(titileL)
        
        dateL = UILabel().then({
            $0.frame = CGRect(x: bgView.width - 180, y: 10, width: 170, height: 20)
            $0.text = ""
            $0.textColor = Color999999
            $0.textAlignment = .right
            $0.font = SYSFONT(ofSize: 14)
        })
        bgView.addSubview(dateL)
        
        detailL = YYLabel().then({
            $0.frame = CGRect(x: 10, y: 40, width: bgView.width - 20, height: 40)
            $0.text = "练习健美操十分钟 中间间歇两分钟 此计划在于复习巩固 晚上慢跑十五分钟。 "
            $0.textVerticalAlignment = .top
            $0.numberOfLines = 2
            $0.textColor = Color666666
            $0.font = SYSFONT(ofSize: 13)
        })
        bgView.addSubview(detailL)
    }
    
    var model = ScheduleListModel() {
        didSet {
            titileL.text = model.class_name
            detailL.text = model.title
            
            guard model.starttime.count > 4 else {
                return
            }
            let startStr = model.starttime.suffix(14)
            let leftDate = startStr.prefix(11)
            let endStr = model.endtime.suffix(8)
            let rightData = endStr.prefix(5)
            dateL.text = "\(leftDate)~\(rightData)"
            
            let color = UIColor.rgbConversionColorl(rgbStr: model.color)
            titileL.textColor = color
            bgView.backgroundColor = color.withAlphaComponent(0.2)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}

